package com.example.forum.exception;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;


@ControllerAdvice
public class CommonExceptionHandler {
    //处理全局异常
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Map<String,String> exceptionHandler(Throwable e){
    e.printStackTrace();
    Map<String, String>result=new HashMap<>();
    result.put("code","ERROR");
    result.put("message",e.getMessage());
    result.put("data",null);
    return result;
    }

    //专门处理绑定的异常
    @ExceptionHandler(BindException.class)
    //此注解是返回json格式数据
    @ResponseBody
    public Map<String,String> exceptionHandler(BindException e){
        e.printStackTrace();
        Map<String,String> result=new HashMap<>();
        result.put("code","error");
        result.put("message",e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        result.put("data",null);
        return result;
//        return e.getMessage();
    }

}
